<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 采购单入库列表
 * @package app\cms\admin
 */
class PurchaseWarehousing extends Admin
{
    // 模型初始化
    protected static function init()
    {
        //TODO:初始化内容
    }

    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
		
		//tab
        $list_tab = [
            'tab1' => ['title' => '采购中', 'url' => url('index', ['group' => 'tab1'])],
            'tab2' => ['title' => '已入库', 'url' => url('index', ['group' => 'tab2'])],
        ];

        // 数据列表
        $group = isset($data['group']) ? $data['group'] : 'tab1';
        switch ($group) {
            case 'tab1':
                $map[] = ['purchase_status', '=', 1];
                break;
			case 'tab2':
                $map[] = ['purchase_status', '=', 2];
                break;
        }
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		$map1 = [];
		if($sotre_user['store_uid'] > 0){
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id = $store_warehouse_list[0];
			$map[] = ['arrival_warehouse_id', '=', $warehouse_id];
			$map1[] = ['id', '=', $warehouse_id];
		}
		
        //数据列表
		$data_list = model('ErpGoodsPurchaseOrder', 'model') -> where($map) -> order('purchase_status asc,create_time desc') -> paginate();
		
		$btn_details = [
			'title' => '详情',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('details', ['id' => '__id__']),
		];
		
		$btn_add = [
			'title' => '入库操作',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('add', ['id' => '__id__']),
		];
		
		$btn_access = [
			'title' => '创建采购单',
			'icon'  => 'fa fa-plus-circle',
			'class' => 'btn btn-primary',
			'href'  => url('purchase/add'),
		];
		// $warehouse_list = model('ErpWarehouse') -> where('type', 2) -> order('type desc') -> column('id,title');
		$warehouse_list = model('ErpWarehouse') -> where($map1) -> order('type desc') -> column('id,title');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('采购单列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_purchase_order') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['title', '采购单名称'],
                ['code', '采购单编号'],
                // ['supplier_id', '供应商'],
                // ['procurement_method', '采购方式', [1=>'现购', 2=>'赊购']],
                // ['arrival_warehouse_id', '到货仓'],
                // ['advance_charge', '预付款'],
                ['arrival_days', '到货天数'],
                ['remark', '备注'],
                ['handled_by', '经办人'],
                ['purchase_status', '采购单状态', 'status', '', [1 => '采购中:warning', 2 => '已入库:success']],
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([
				['select', 'arrival_warehouse_id', '选择仓库', '', '',  $warehouse_list],
                ['text', 'title', '采购单名称', 'like'],
				['text', 'code', '采购单编号', 'like'],
                ['text', 'handled_by', '经办人', 'like'],
				// ['select', 'procurement_method', '采购方式', '', '', [1 => '现购', 2=>'赊购']],
				// ['select', 'purchase_status', '采购单状态', '', '', [1 => '采购中', 2 => '已入库']],
				['daterange', 'create_time', '创建时间'],
            ])
			->addTopButton('custom', $btn_access) // 添加授权按钮
            ->addRightButton('btn_add', $btn_add) // 批量添加右侧按钮
            ->addRightButton('custom', $btn_details, true) // 批量添加右侧按钮
			->replaceRightButton(['purchase_status' => 2], '', ['btn_add'])
			->setTabNav($list_tab, $group)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面

    }

	/**
     * 添加商品数量
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add($id = ''){
		DB::startTrans();//启动事务
		
		 if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
			
			$rk_remark      = isset($data['rk_remark']) ? $data['rk_remark'] : '';
            $rk_handled_by  = isset($data['rk_handled_by']) ? $data['rk_handled_by'] : '';
			if($rk_handled_by == '') $this->error('请输入入库经办人');

			unset($data['__token__']);
			unset($data['title']);
			unset($data['supplier_title']);
			// unset($data['procurement_method']);
			unset($data['arrival_warehouse_id']);
			// unset($data['advance_charge']);
			unset($data['arrival_days']);
			unset($data['remark']);
			unset($data['handled_by']);
			unset($data['rk_remark']);
			unset($data['rk_handled_by']);

			//校验采购单
			$order_code = model('ErpGoodsPurchaseOrder', 'model') -> find($id);
			if(empty($order_code) || $order_code['purchase_status'] != 1){
				DB::rollback();
				$this->error('不存在采购单'); // 不存在采购单
			}

			//入库操作 - 插入操作记录
			$code 			= $order_code['code'];
			$warehouse_id 	= $order_code['arrival_warehouse_id'];//仓库id
			$rel = model('ErpGoodsWarehousing', 'model') -> addData(1, $id, $rk_handled_by, $rk_remark, $code);
			if($rel['code'] < 0){
				DB::rollback();
				$this->error($rel['message']);
			}
			
			$sku_arr = [];
			foreach($data as $key => $value){
				$sku_info = explode('/', $key);
				$sku_id   = $sku_info[1]; //商品skuid
				
				$map = [];
				$map['purchase_id'] = $id;
				$map['sku_id'] 		= $sku_id;
				$purchase_sku = model('ErpGoodsPurchaseOrderSku', 'model') -> where($map) -> find();
				
				//组合sku信息
				$sku_arr[$sku_id]['id'] 	= $purchase_sku['id'];
				$sku_arr[$sku_id]['sku_id'] = $sku_id;
				
				if($sku_info[0] == 'rk_num'){
					if($value == ''){
						DB::rollback();
						$this->error('请输入商品入库库存！');
					} 
					if($value > $purchase_sku['num']){
						DB::rollback();
						$this->error('入库数量不能大于采购数量！');
					}
					$sku_arr[$sku_id]['rk_num'] = $value;
				}
				
				if($sku_info[0] == 'remark'){
					$sku_arr[$sku_id]['remark'] = $value;
				}	
			}
			$rel = model('ErpGoodsPurchaseOrderSku') -> saveAll($sku_arr);//dump($rel);
			if(!$rel){
				DB::rollback();
				$this->error('插入失败，请重试');
			}
			
			foreach($sku_arr as $key => $value){
				//计算库存
				$map = [];
				$map['warehouse_id'] = $warehouse_id;
				$map['sku_id'] 		 = $value['sku_id'];
				$warehouse_num = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();//获取仓库数量
				
				if(empty($warehouse_num)){//插入库存
					$sku_info = model('ErpGoodsSku') -> where('id', $value['sku_id']) -> find();//商品sku - 获取价格
					$rel = model('ErpGoodsWarehouseStockNum') -> addData($warehouse_id, $value['sku_id'], $value['rk_num'], $value['rk_num'], $sku_info['goods_id'], $sku_info['price']);
				}else{//更新库存
					$stock_num 		= $warehouse_num['stock_num'] + $value['rk_num'];//总库存
					$available_num  = $stock_num - $warehouse_num['frozen_num'];//可用库存
					$rel = model('ErpGoodsWarehouseStockNum') -> editData($warehouse_num['id'], $warehouse_id, $value['sku_id'], $stock_num, '', $available_num);
				}
				if($rel['code'] < 0){
					DB::rollback();
					$this->error('更新库存失败，请重试');
				}
			}
			
			$map = [];
			$map['id'] = $id;
			$data = [];
			$data['purchase_status'] = 2;
             //获取回款日期
             if(!empty($order_code['supplier_id'])){
                 $supplier_infos = model('ErpSupplier','model') ->where('id',$order_code['supplier_id'])-> column('id,settlement_cycle,jiesuan_type,bank_account,rebate');
                 $supplier_info = $supplier_infos[$order_code['supplier_id']];
                 if($supplier_info['jiesuan_type'] == 1){
                     // 货到N日内付款
                     $data['back_date'] = strtotime(date('Y-m-d 23:59:59',time())) + $supplier_info['settlement_cycle']*24*3600;
                 }else{
                     //$data['back_date'] = '';
				 }
				 //dump($data['back_date']);
                 if(!empty($data['back_date']) && $data['back_date'] < time() && $supplier_info['jiesuan_type'] == 1){
                     $this->error('回款时间不能小于当前时间');
                 }
             }
			$res = model('ErpGoodsPurchaseOrder') ->update($data, $map);//更新采购单状态
			if($rel['code'] < 0){
				DB::rollback();
				$this->error('采购单更新失败，请重试');
			}else{
			    //插入采购单相关统计数据到回款表
                $purchase_id = $id;
                if(isset($supplier_infos) && !empty($supplier_infos)){
                    $supplier_id = $supplier_info['id'];
                    $supplier_rebate = $supplier_info['rebate'];
                    $supplier_bank_account = $supplier_info['bank_account'];
                }
                $sum_pay_cg = model('ErpGoodsPurchaseOrderSku','model')->reckonCg($id);
                $purchase_sum_cg = $sum_pay_cg['data']?:0;
                $sum_pay_rk = model('ErpGoodsPurchaseOrderSku','model')->reckonRk($id);
                $purchase_sum_rk = $sum_pay_rk['data']?:0;
                $pay_sum = '';
                $pay_time = '';
                $rel_back = model('ErpGoodsPurchaseOrderBack','model')->addData($purchase_id, $supplier_id, $supplier_rebate, $supplier_bank_account,$purchase_sum_cg, $purchase_sum_rk, $pay_sum='', $pay_time='', $pay_status=0);
				DB::commit();
				$this->success('申请成功', cookie('__forward__'));
			}
        }
		
		$goods_sku_id = model('ErpGoodsPurchaseOrderSku') -> where('purchase_id', $id) -> column('sku_id,num');
		$table_data = [
			['采购商品', '预计采购数量', '实际入库数量', '备注'],
		];
		foreach($goods_sku_id as $key => $value){
			$sku_info = model('ErpGoodsSku') -> find($key);
			if($sku_info['goods_specifications'] != ''){
				$goods_name = $sku_info['goods_name'] . ' - ' . $sku_info['goods_specifications'];
			}else{
				$goods_name = $sku_info['goods_name'];
			}
			$table_data[] = [$goods_name, $value, '<input type="text" name="rk_num/'. $sku_info['id'] .'" />', '<input type="text" name="remark/'. $sku_info['id'] .'" />'];
		}
		$info = model('ErpGoodsPurchaseOrder') -> find($id);
		$info['supplier_title'] 	= model('ErpSupplier') -> find($info['supplier_id']) -> title;
		// $info['procurement_method'] = $info['procurement_method'] == 1 ? '现购' : '赊购';
		$info['arrival_warehouse_id']= model('ErpWarehouse') -> find($info['arrival_warehouse_id']) -> title;
       // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('采购单申请') // 设置页面标题
            ->addFormItems([
				['text', 'title', '采购单名称', '', '', '', 'readonly="readonlys"'],
				['text', 'supplier_title', '供应商', '', '', '', 'readonly="readonlys"'],
				// ['text', 'procurement_method', '采购方式', '', '', '', 'readonly="readonlys"'],
				['text', 'arrival_warehouse_id', '到货仓', '', '', '', 'readonly="readonlys"'],
				// ['text', 'advance_charge', '预付款', '', '', '', 'readonly="readonlys"'],
				['text', 'arrival_days', '到货天数', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '采购单备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '采购经办人', '', '', '', 'readonly="readonlys"'],
				['text', 'rk_remark', '入库备注'],
				['text', 'rk_handled_by', '入库经办人', '', get_nickname(UID)],
			])
			->setFormData($info) // 设置表单数据
			->addFormItems([ // 批量添加表单项
				['complexTable', 'list_user', '采购单sku', $table_data]
			])
            ->fetch();
    }
	
	//采购单详情
	public function details($id = []){
		$info = model('ErpGoodsPurchaseOrder') -> find($id);
		$info['supplier_title'] 	= model('ErpSupplier') -> find($info['supplier_id']) -> title;
		// $info['procurement_method'] = $info['procurement_method'] == 1 ? '现购' : '赊购';
		$arrival_warehouse= model('ErpWarehouse') -> find($info['arrival_warehouse_id']);
		$info['arrival_warehouse'] = !empty($arrival_warehouse) ? $arrival_warehouse['title'] : '仓库已注销';
		
		$table_data = [
			['sku_id', '采购商品', '采购价格', '预计采购数量', '实际入库数量', '备注'],
		];
		$purchase_sku = model('ErpGoodsPurchaseOrderSku') -> where('purchase_id', $id) -> column('sku_id,num,price,rk_num,remark');
		foreach($purchase_sku as $value){
			$goods_info = model('ErpGoodsSku') -> find($value['sku_id']);
			if($goods_info['goods_specifications'] != ''){
				$goods_name = $goods_info['goods_name'] . ' - ' . $goods_info['goods_specifications'];
			}else{
				$goods_name = $goods_info['goods_name'];
			}
			
			$table_data[] = [$value['sku_id'], $goods_name, $value['price'], $value['num'], $value['rk_num'], $value['remark']];
		}
		$ware_info = model('ErpGoodsWarehousing') -> where('code', $info['code']) -> find();
		$info['rk_remark'] = $ware_info['remark'];
		$info['rk_handled_by'] = $ware_info['handled_by'];
		//批量审核最多允许20个
		return ZBuilder::make('form')
            ->setPageTitle('采购单详情') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
				['text', 'title', '采购单名称', '', '', '', 'readonly="readonlys"'],
				['text', 'supplier_title', '供应商', '', '', '', 'readonly="readonlys"'],
				// ['text', 'procurement_method', '采购方式', '', '', '', 'readonly="readonlys"'],
				['text', 'arrival_warehouse', '到货仓', '', '', '', 'readonly="readonlys"'],
				// ['text', 'advance_charge', '预付款', '', '', '', 'readonly="readonlys"'],
				['text', 'arrival_days', '到货天数', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '采购备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '采购经办人', '', '', '', 'readonly="readonlys"'],
				['complexTable', 'list_user', '采购单sku', $table_data],
				['text', 'rk_remark', '入库备注', '', '暂未入库', '', 'readonly="readonlys"'],
				['text', 'rk_handled_by', '入库经办人', '', '暂未入库', '', 'readonly="readonlys"'],
			])
			->hideBtn(['submit', 'back'])
			->setFormData($info) // 设置表单数据
            ->fetch();
	}
}